package top.winshu.common.web;

import top.winshu.common.constant.ExceptionCode;

import java.io.Serializable;

/**
 * 返回消息
 *
 * @author winshu
 * @since 2020/9/15
 **/
public class RestResponse<E> implements Serializable {

    // 成功
    public static final String SUCCESS = "0";

    public static <T> RestResponse<T> success() {
        return success("成功");
    }

    public static <T> RestResponse<T> success(String message) {
        return success(message, null);
    }

    public static <T> RestResponse<T> success(T data) {
        return success("成功", data);
    }

    public static <T> RestResponse<T> success(String message, T data) {
        return new RestResponse<>(SUCCESS, message, null, data);
    }

    public static <T> RestResponse<T> fail() {
        return fail("失败");
    }

    /**
     * 默认异常
     */
    public static <T> RestResponse<T> fail(String message) {
        return fail(ExceptionCode.DEFAULT, message, RestResponse.class.getName());
    }

    /**
     * 其他异常
     */
    public static <T> RestResponse<T> fail(String message, Throwable e) {
        String stack = e.getClass().getName() + "/" + (e.getMessage() == null ? "" : e.getMessage());
        return fail(ExceptionCode.DEFAULT, message, stack);
    }

    /**
     * 自定义异常
     *
     * @param code    状态码，建议小于零
     * @param message 错误提示内容
     * @param stack   堆栈错误内容
     */
    public static <T> RestResponse<T> fail(String code, String message, String stack) {
        if (code == null || code.isEmpty()) {
            return new RestResponse<>(ExceptionCode.DEFAULT, "状态码错误，代码问题", stack, null);
        }
        return new RestResponse<>(code, message, stack, null);
    }

    // 状态码
    private String code;

    // 用于提示的消息
    private String message;

    // 后台返回的异常栈内容
    private String stack;

    // 数据体
    private E data;

    private RestResponse(String code, String message, String stack, E data) {
        this.code = code;
        this.message = message;
        this.stack = stack;
        this.data = data;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getStack() {
        return stack;
    }

    public void setStack(String stack) {
        this.stack = stack;
    }

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }

}
